package com.zxy.ziems.common.utils;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

/**
 * @author 10348359
 * @create 2024-04-12 11:53
 */
public class IPUtils {
    public IPUtils() {
    }


    public static String getLocalAddress() {
        try {
            InetAddress inetAddress = getLocalInetAddress();
            return inetAddress.getHostAddress();
        } catch (Exception var1) {
            return "unkown";
        }
    }

    public static String getLocalMac() {
        try {
            InetAddress inetAddress = getLocalInetAddress();
            byte[] mac = NetworkInterface.getByInetAddress(inetAddress).getHardwareAddress();
            StringBuilder sBuilder = new StringBuilder("");

            for(int i = 0; i < mac.length; ++i) {
                if (i != 0) {
                    sBuilder.append("-");
                }

                int temp = mac[i] & 255;
                String str = Integer.toHexString(temp);
                if (str.length() == 1) {
                    sBuilder.append("0" + str);
                } else {
                    sBuilder.append(str);
                }
            }

            return sBuilder.toString().toUpperCase();
        } catch (Exception var6) {
            return "unkown";
        }
    }

    public static InetAddress getLocalInetAddress() throws Exception {
        InetAddress candidateAddress = null;
        Enumeration ifaces = NetworkInterface.getNetworkInterfaces();

        while(ifaces.hasMoreElements()) {
            NetworkInterface iface = (NetworkInterface)ifaces.nextElement();
            Enumeration inetAddrs = iface.getInetAddresses();

            while(inetAddrs.hasMoreElements()) {
                InetAddress inetAddr = (InetAddress)inetAddrs.nextElement();
                if (!inetAddr.isLoopbackAddress()) {
                    if (inetAddr.isSiteLocalAddress()) {
                        return inetAddr;
                    }

                    if (candidateAddress == null) {
                        candidateAddress = inetAddr;
                    }
                }
            }
        }

        if (candidateAddress != null) {
            return candidateAddress;
        } else {
            InetAddress jdkSuppliedAddress = InetAddress.getLocalHost();
            return jdkSuppliedAddress;
        }
    }
}